import PQueue from 'p-queue';

export class RequestQueue {
  #queue;

  constructor(concurrency = 5) {
    this.#queue = new PQueue({
      concurrency,
      autoStart: true,
      throwOnTimeout: false
    });
  }

  async add(fn, config) {
    return this.#queue.add(fn, {
      priority: config.priority || 0,
      retry: {
        retries: config.retry || 0,
        onFailedAttempt: error => {
          console.error(
            `Request failed, attempt ${error.attemptNumber}. ${error.retriesLeft} retries left.`
          );
        }
      }
    });
  }

  clear() {
    this.#queue.clear();
  }

  get size() {
    return this.#queue.size;
  }

  get pending() {
    return this.#queue.pending;
  }
}